<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\scanwork\Config as ConfigModel;
use think\Exception;

/**
 * 报工接口
 */
class Baogong extends Api
{
    protected $noNeedLogin = ['wechatLogin'];
    protected $noNeedRight = ['*'];
    
    /**
     * 微信登录
     */
    public function wechatLogin()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('缺少参数code');
        }
        
        try {
            // 从配置系统获取微信小程序的appid和secret
            $appid = ConfigModel::getMiniappAppid();
            $secret = ConfigModel::getMiniappSecret();
            
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
            $result = json_decode(curl_get_contents($url), true);
            
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                $this->error('微信登录失败: ' . $result['errmsg']);
            }
            
            // 检查用户是否存在
            $user = \app\common\model\User::where(['openid' => $result['openid']])->find();
            
            if (!$user) {
                // 创建新用户
                $user = \app\common\model\User::create([
                    'username' => 'wx_' . $result['openid'],
                    'nickname' => '微信用户',
                    'openid' => $result['openid'],
                    'wechat_unionid' => isset($result['unionid']) ? $result['unionid'] : '',
                    'group_id' => 0, // 未绑定状态
                    'status' => 'normal'
                ]);
            }
            
            // 生成token
            $token = \fast\Random::uuid();
            $user->token = $token;
            $user->save();
            
            $this->success('登录成功', [
                'token' => $token,
                'user' => $user->toArray()
            ]);
        } catch (Exception $e) {
            $this->error('登录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 绑定FastAdmin用户
     */
    public function bindUser()
    {
        $token = $this->request->header('Token');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        
        if (!$token || !$username || !$password) {
            $this->error('缺少必要参数');
        }
        
        try {
            // 验证token
            $user = \app\common\model\User::where(['token' => $token])->find();
            if (!$user) {
                $this->error('无效的token');
            }
            
            // 验证FastAdmin用户
            $adminUser = \app\common\model\User::where(['username' => $username])->find();
            if (!$adminUser) {
                $this->error('用户不存在');
            }
            
            // 验证密码
            if (!\fast\Auth::checkPassword($password, $adminUser['password'], $adminUser['salt'])) {
                $this->error('密码错误');
            }
            
            // 更新绑定信息
            $user->group_id = $adminUser->group_id;
            $user->bind_admin_id = $adminUser->id;
            $user->save();
            
            $this->success('绑定成功', [
                'user' => $user->toArray()
            ]);
        } catch (Exception $e) {
            $this->error('绑定失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取任务列表
     */
    public function getTasks()
    {
        $token = $this->request->header('Token');
        if (!$token) {
            $this->error('缺少token');
        }
        
        try {
            $user = \app\common\model\User::where(['token' => $token])->find();
            if (!$user) {
                $this->error('无效的token');
            }
            
            // 检查是否已绑定
            if ($user->group_id == 0) {
                $this->error('请先绑定FastAdmin用户', null, 403);
            }
            
            // 获取分配给该用户的任务
            $tasks = \app\admin\model\Allocation::with(['order', 'model', 'process'])
                ->where(['user_id' => $user->bind_admin_id])
                ->where(['status' => 0])
                ->select();
            
            $this->success('获取成功', [
                'tasks' => $tasks
            ]);
        } catch (Exception $e) {
            $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 提交报工
     */
    public function submitReport()
    {
        $token = $this->request->header('Token');
        $allocationId = $this->request->post('allocation_id');
        $quantity = $this->request->post('quantity');
        $remark = $this->request->post('remark', '');
        
        if (!$token || !$allocationId || !$quantity) {
            $this->error('缺少必要参数');
        }
        
        try {
            $user = \app\common\model\User::where(['token' => $token])->find();
            if (!$user) {
                $this->error('无效的token');
            }
            
            // 检查是否已绑定
            if ($user->group_id == 0) {
                $this->error('请先绑定FastAdmin用户', null, 403);
            }
            
            // 检查分配记录
            $allocation = \app\admin\model\Allocation::with(['order', 'model', 'process'])
                ->where(['id' => $allocationId, 'user_id' => $user->bind_admin_id])
                ->find();
            
            if (!$allocation) {
                $this->error('分配记录不存在');
            }
            
            // 创建报工记录
            $report = \app\admin\model\Report::create([
                'allocation_id' => $allocationId,
                'quantity' => $quantity,
                'remark' => $remark,
                'user_id' => $user->bind_admin_id,
                'status' => 1 // 已提交
            ]);
            
            $this->success('报工提交成功', [
                'report_id' => $report->id
            ]);
        } catch (Exception $e) {
            $this->error('提交失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取任务详情
     */
    public function getTaskInfo()
    {
        $token = $this->request->header('Token');
        $id = $this->request->get('id');
        
        if (!$token || !$id) {
            $this->error('缺少必要参数');
        }
        
        try {
            $user = \app\common\model\User::where(['token' => $token])->find();
            if (!$user) {
                $this->error('无效的token');
            }
            
            // 检查是否已绑定
            if ($user->group_id == 0) {
                $this->error('请先绑定FastAdmin用户', null, 403);
            }
            
            // 获取分配记录
            $task = \app\admin\model\Allocation::with(['order', 'model', 'process'])
                ->where(['id' => $id, 'user_id' => $user->bind_admin_id])
                ->find();
            
            if (!$task) {
                $this->error('任务不存在');
            }
            
            $this->success('获取成功', [
                'task' => $task
            ]);
        } catch (Exception $e) {
            $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取报工记录
     */
    public function getRecords()
    {
        $token = $this->request->header('Token');
        
        if (!$token) {
            $this->error('缺少token');
        }
        
        try {
            $user = \app\common\model\User::where(['token' => $token])->find();
            if (!$user) {
                $this->error('无效的token');
            }
            
            // 检查是否已绑定
            if ($user->group_id == 0) {
                $this->error('请先绑定FastAdmin用户', null, 403);
            }
            
            // 获取报工记录
            $records = \app\admin\model\Report::with(['allocation.order', 'allocation.model', 'allocation.process'])
                ->where(['user_id' => $user->bind_admin_id])
                ->order('id', 'desc')
                ->select();
            
            $this->success('获取成功', [
                'records' => $records
            ]);
        } catch (Exception $e) {
            $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取工资信息
     */
    public function getWages()
    {
        $token = $this->request->header('Token');
        
        if (!$token) {
            $this->error('缺少token');
        }
        
        try {
            $user = \app\common\model\User::where(['token' => $token])->find();
            if (!$user) {
                $this->error('无效的token');
            }
            
            // 检查是否已绑定
            if ($user->group_id == 0) {
                $this->error('请先绑定FastAdmin用户', null, 403);
            }
            
            // 获取当前月份
            $month = date('Y-m');
            
            // 获取报工记录并计算工资
            $reports = \app\admin\model\Report::with(['allocation.order', 'allocation.model', 'allocation.process'])
                ->where(['user_id' => $user->bind_admin_id])
                ->whereRaw("DATE_FORMAT(FROM_UNIXTIME(createtime), '%Y-%m') = ?", [$month])
                ->select();
            
            $wages = [];
            $totalWage = 0;
            
            foreach ($reports as $report) {
                // 计算单条记录的工资（这里假设有一个price字段表示单价）
                $price = $report->allocation->process->price ?? 0;
                $quantity = $report->quantity;
                $wage = $price * $quantity;
                
                $wages[] = [
                    'id' => $report->id,
                    'order_sn' => $report->allocation->order->order_sn ?? '',
                    'model_name' => $report->allocation->model->name ?? '',
                    'process_name' => $report->allocation->process->name ?? '',
                    'quantity' => $quantity,
                    'price' => $price,
                    'wage' => $wage,
                    'createtime' => $report->createtime
                ];
                
                $totalWage += $wage;
            }
            
            $this->success('获取成功', [
                'wages' => $wages,
                'totalWage' => $totalWage,
                'month' => $month
            ]);
        } catch (Exception $e) {
            $this->error('获取失败: ' . $e->getMessage());
        }
    }
}